package com.ruoyi.data.filter.first;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.core.domain.entity.data.AccessBody;
import com.ruoyi.data.filter.GetBeanUtil;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Component
public class AccessTokenService {

    // 令牌自定义标识
    @Value("${accessToken.header}")
    private String header;

    // 令牌秘钥
    @Value("${accessToken.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${accessToken.expireTime}")
    private int expireTime;



    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private RedisCache redisCache;


    /**
     * 创建令牌
     *
     * @param accessBody
     * @return 令牌
     */
    public String createAccessToken(AccessBody accessBody)
    {
        String token = IdUtils.fastUUID();
        accessBody.setAccessToken(token);
        setAgent(accessBody);
        refreshToken(accessBody);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.ACCESS_TOKEN, token);
        return createToken(claims);
    }


    /**
     * 设置用户代理信息
     *
     * @param accessBody
     */
    public void setAgent(AccessBody accessBody)
    {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        accessBody.setIpaddr(ip);
        accessBody.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        accessBody.setBrowser(userAgent.getBrowser().getName());
        accessBody.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 刷新令牌有效期
     *
     * @param accessBody
     */
    public void refreshToken(AccessBody accessBody)
    {
        accessBody.setLoginTime(System.currentTimeMillis());
        accessBody.setExpireTime(accessBody.getLoginTime() + 30 * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(accessBody.getAccessToken());
        redisCache.setCacheObject(userKey, accessBody, 30, TimeUnit.MINUTES);
    }

    private String getTokenKey(String uuid)
    {
        return Constants.ACCESS_TOKEN + uuid;
    }


    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims)
    {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

    /**
     * 从令牌中获取
     * @param request
     * @return
     */
    public AccessBody getAccessBody(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            try
            {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(Constants.ACCESS_TOKEN);
                String accessToken = getTokenKey(uuid);
//                AccessBody accessBody = redisCache.getCacheObject(accessToken);
                AccessBody accessBody = GetBeanUtil.getBean(RedisCache.class).getCacheObject(accessToken);
                return accessBody;
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     *  获取请求acces_token
     * @param request
     * @return
     */
    private String getToken(HttpServletRequest request)
    {
        try{
            String token = request.getHeader(header);
            if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
            {
                token = token.replace(Constants.TOKEN_PREFIX, "");
            }
            return token;
        }catch (Exception e){
            return null;
        }

    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token)
    {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param accessBody
     * @return 令牌
     */
    public void verifyToken(AccessBody accessBody)
    {
        long expireTime = accessBody.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
        {
            refreshToken(accessBody);
        }
    }
}
